﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using System.Data;
using Newtonsoft.Json.Converters;
using System.Text;
using Newtonsoft.Json.Linq;
using System.IO;
using DBUtility;
using System.Text.RegularExpressions;
using System.Drawing;
using EFDataBase;
using EFDataBase.Models;
using System.Runtime.Serialization;

namespace YiDaShuiHang
{
    /// <summary>
    /// Handler1 的摘要说明
    /// </summary>
    public class Handler1 : System.Web.UI.Page, IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            string result = "";
            context.Response.ContentType = "text/plain";
            string types = "";
            string htmldata = "";
            string newguid = "";
            string customerdata = "";
            string productdata = "";
            string code = "";
            string username = "";
            string pagecurrent = "";
            string indexwhere = "";
            string resoretype = "";
            string password = "";
            DataTable backhtml;
            string[] htmldata_areey;
            int record_count = 0;
            string[] productdata_areey;
            try
            {
                string poststr = getpost();
                if (!string.IsNullOrEmpty(poststr))
                {
                    JObject jobj = JObject.Parse(poststr);
                    types = jobject(jobj, "type");
                    username = jobject(jobj, "username");
                    password = jobject(jobj, "password");
                    code = jobject(jobj, "code");
                    pagecurrent = jobject(jobj, "pagecurrent");
                    indexwhere = jobject(jobj, "indexwhere");
                    resoretype = jobject(jobj, "resoretype");
                    htmldata = jobject(jobj, "htmldata");
                    customerdata = jobject(jobj, "customerdata");
                    productdata = jobject(jobj, "productdata");
                    if (types != "")
                    {

                        string resultstr = "";
                        DBUtility.Shopping shop = new DBUtility.Shopping();
                        switch (types)
                        {
                            case "login"://登入页面
                                #region
                                string login_result = commen.login(username, password);
                                if (login_result.Contains("OK"))
                                {
                                    result = "{\"result\":\"ok\",\"msg\":\"成功\"}";
                                }
                                else
                                {
                                    result = "{\"result\":\"error\",\"msg\":\"失败\"}";
                                }
                                #endregion
                                break;
                            case "addproduct":
                                #region
                                newguid = Guid.NewGuid().ToString();
                                string mainimgurl = savePic("img1");
                                htmldata_areey = htmldata.Split('|');
                                string productset = shop.productset(htmldata_areey[2]);//商品类型
                                string parentid = htmldata_areey[2];//这是产品类id
                                Regex r = new Regex("@");
                                productdata = r.Replace(productdata, "\\", 20);
                                productdata_areey = productdata.Split('=');
                                for (int i = 0; i < productdata_areey.Length; i++)
                                {
                                    if (productdata_areey[i].Contains("|"))
                                    {
                                        string[] productdata_areeys = productdata_areey[i].Split('|');
                                        int stock = productdata_areeys[2] == "" ? 20 : int.Parse(productdata_areeys[2]);//库存量
                                        string imagepath = "";
                                        string img = productdata_areeys[3].ToString();
                                        log(productdata_areeys[3]);
                                        imagepath = productdata_areeys[3];
                                        shop.insertProduct_setAttribute(newguid, productdata_areeys[0], htmldata_areey[1], mainimgurl, imagepath, stock, productdata_areeys[1]);
                                    }
                                }
                                shop.addproducts(newguid, parentid, htmldata_areey[0], productset);
                                result = "{\"result\":\"ok\",\"msg\":\"保存成功\"}";
                                #endregion
                                break;
                            case "getaddproduct":
                                backhtml = shop.getaddproduct();
                                result = "{\"result\":\"ok\",\"table\":" + DataTableToJson(backhtml) + "}";
                                break;
                            case "savechildimg":
                                string imgpath = savePic2("img2");
                                Regex rr = new Regex(@"\\");
                                productdata = rr.Replace(imgpath, "@", 20);
                                result = "{\"result\":\"ok\",\"msg\":\"" + productdata + "\"}";
                                break;
                            case "getopenid":
                                #region
                                string[] appid = System.Configuration.ConfigurationManager.AppSettings["appid_user"].Split('|');
                                string url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid[0] + "&secret=" + appid[1] + "&code=" + code + "&grant_type=authorization_code";
                                log(url);
                                string jj = "";
                                Web_Request net = new Web_Request(url, "GET");
                                string text = net.GetResponseText();
                                log(text);
                                JObject jobj1 = JObject.Parse(text);
                                string openid = jobject(jobj1, "openid");
                                log(openid);
                                net.Dispose();
                                result = "{\"result\":\"ok\",\"msg\":\"" + openid + "\"}";
                                #endregion
                                break;
                            case "aboutobject":
                                backhtml = shop.GetAboutdata(htmldata);
                                result = "{\"result\":\"ok\",\"table\":" + DataTableToJson(backhtml) + "}";
                                break;
                            case "indexdata":
                                #region
                                //ShowProduct product = new ShowProduct();
                                //List<View_product> list = product.GetProduct<View_product>("", "");
                                FactoryIndex fi = new FactoryIndex();
                                ShowProduct sp = fi.GetProduct();
                                string backhtml_ = sp.JsonData(htmldata);
                                result = "{\"result\":\"ok\",\"table\":" + backhtml_ + "}";
                                #endregion
                                break;
                            case "buypagegetdata":
                                htmldata_areey = htmldata.Split('|');
                                backhtml = shop.Getbuydata(htmldata, resoretype);
                                DataTable userdata = shop.Getuserdata(htmldata_areey[htmldata_areey.Length - 1]);
                                result = "{\"result\":\"ok\",\"table\":" + DataTableToJson(backhtml) + ",\"userdata\":" + DataTableToJson(userdata) + "}";
                                break;
                            case "submitOrder":
                                string guid = Guid.NewGuid().ToString();
                                shop.submitOrder(htmldata, guid, customerdata);
                                //shop.insertcustom(customerdata, guid);
                                result = "{\"result\":\"ok\",\"msg\":\"保存成功，我们会尽快送到宿舍\"}";
                                break;
                            case "showpinghcar":
                                backhtml = shop.Getshowpingcar(htmldata);
                                result = "{\"result\":\"ok\",\"table\":" + DataTableToJson(backhtml) + "}";
                                break;
                            case "addshowpinghcar":
                                shop.addshowpinghcar(htmldata);
                                result = "{\"result\":\"ok\",\"msg\":\"添加成功\"}";
                                break;
                            case "orderpage":
                                backhtml = shop.Getorderpage(htmldata);
                                result = "{\"result\":\"ok\",\"table\":" + DataTableToJson(backhtml) + "}";
                                break;
                            case "orderpagexiugai":
                                htmldata_areey = htmldata.Split('|');
                                Sqlopenhander adoh = new Sqlopenhander();
                                adoh.Sqlcmd = htmldata_areey[0];
                                adoh.ExecuteSqlNonQuery();
                                backhtml = shop.Getorderpage(htmldata_areey[1]);
                                result = "{\"result\":\"ok\",\"table\":" + DataTableToJson(backhtml) + "}";
                                break;
                            case "ordermanager":
                                backhtml = shop.Getordermanager(int.Parse(pagecurrent), indexwhere, ref record_count);
                                result = "{\"result\":\"ok\",\"msg\":\"成功\",\"record_count\":\"" + record_count + "\",\"page_curent\":\"" + pagecurrent + "\",\"table\":" + DataTableToJson(backhtml) + "}";
                                break;
                            case "handleordermanager":
                                shop.handleordermanager(htmldata);
                                result = "{\"result\":\"ok\",\"msg\":\"添加成功\",\"id\":\"" + htmldata + "\"}";
                                break;
                            case "deleteshoppingcar":
                                shop.deleteshoppingcar(htmldata);
                                htmldata_areey = htmldata.Split('|');
                                backhtml = shop.Getshowpingcar(htmldata_areey[0]);
                                result = "{\"result\":\"ok\",\"msg\":\"添加成功\",\"table\":" + DataTableToJson(backhtml) + "}";
                                break;
                            case "goodmanager":
                                backhtml = shop.goodmanager(int.Parse(pagecurrent), indexwhere, ref record_count);
                                result = "{\"result\":\"ok\",\"msg\":\"成功\",\"record_count\":\"" + record_count + "\",\"page_curent\":\"" + pagecurrent + "\",\"table\":" + DataTableToJson(backhtml) + "}";
                                break;
                            case "classifiedmanager":
                                backhtml = shop.classifiedmanager(int.Parse(pagecurrent), indexwhere, ref record_count);
                                result = "{\"result\":\"ok\",\"msg\":\"成功\",\"record_count\":\"" + record_count + "\",\"page_curent\":\"" + pagecurrent + "\",\"table\":" + DataTableToJson(backhtml) + "}";
                                break;
                            case "manmanager":
                                backhtml = shop.manmanager(int.Parse(pagecurrent), indexwhere, ref record_count);
                                result = "{\"result\":\"ok\",\"msg\":\"成功\",\"record_count\":\"" + record_count + "\",\"page_curent\":\"" + pagecurrent + "\",\"table\":" + DataTableToJson(backhtml) + "}";
                                break;
                            case "aftersale":
                                backhtml = shop.aftersale(int.Parse(pagecurrent), indexwhere, ref record_count);
                                result = "{\"result\":\"ok\",\"msg\":\"成功\",\"record_count\":\"" + record_count + "\",\"page_curent\":\"" + pagecurrent + "\",\"table\":" + DataTableToJson(backhtml) + "}";
                                break;
                            case "handleaftersale":
                                Sqlopenhander doh = new Sqlopenhander();
                                doh.Sqlcmd = htmldata;
                                int counts = doh.ExecuteSqlNonQuery();
                                backhtml = shop.aftersale(1, indexwhere, ref record_count);
                                result = "{\"result\":\"ok\",\"msg\":\"成功\",\"record_count\":\"" + record_count + "\",\"page_curent\":\"" + pagecurrent + "\",\"table\":" + DataTableToJson(backhtml) + "}";
                                break;
                            case "handleoneexcute":
                                Sqlopenhander doh1 = new Sqlopenhander();
                                doh1.Sqlcmd = htmldata;
                                int h = doh1.ExecuteSqlNonQuery();
                                if (h > 0)
                                {
                                    resultstr = "成功";
                                }
                                else
                                {
                                    resultstr = "失败";
                                }
                                result = "{\"result\":\"ok\",\"msg\":\"" + resultstr + "\"}";
                                break;
                            case "classifiedmanagerhandleoneexcute":
                                Sqlopenhander doh2 = new Sqlopenhander();
                                doh2.Sqlcmd = htmldata;
                                int count = doh2.ExecuteSqlNonQuery();
                                if (count > 0)
                                {
                                    resultstr = "成功";
                                }
                                else
                                {
                                    resultstr = "失败";
                                }
                                backhtml = shop.classifiedmanager(1, indexwhere, ref record_count);
                                result = "{\"result\":\"ok\",\"msg\":\"成功\",\"record_count\":\"" + record_count + "\",\"page_curent\":\"" + "1" + "\",\"table\":" + DataTableToJson(backhtml) + "}";
                                break;
                            case "manmanagerhandleoneexcute":
                                Sqlopenhander doh4 = new Sqlopenhander();
                                doh4.Sqlcmd = htmldata;
                                doh4.ExecuteSqlNonQuery();
                                backhtml = shop.manmanager(1, indexwhere, ref record_count);
                                result = "{\"result\":\"ok\",\"msg\":\"成功\",\"record_count\":\"" + record_count + "\",\"page_curent\":\"" + pagecurrent + "\",\"table\":" + DataTableToJson(backhtml) + "}";
                                break;
                            default:
                                result = "{\"result\":\"ok\",\"msg\":\"参数错误\"}";
                                break;
                        }
                    }
                    else
                    {

                    }
                }

            }

            catch (Exception ex)
            {
                result = "{\"result\":\"error\",\"msg\":\"" + ex.Message + "\"}";
            }

            context.Response.Write(result);


        }
        public static void log(string content)
        {
            ErrorLog.Log(commen.MapPath_mj("MJLogs/" + DateTime.Now.ToString("yyyyMMdd")), DateTime.Now.ToString() + content);


        }


        #region

        /// <summary>
        /// 这个也是转换为json不过是用系统的
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public string DataTableToJson(DataTable dt)
        {
            string result = "";
            result = JsonConvert.SerializeObject(dt, new DataTableConverter());
            //new DataTableConverter()一般是固定的
            return result;
        }
        /// <summary>     
        /// dataTable转换成Json格式     
        /// </summary>     
        /// <param name="dt"></param>     
        /// <returns></returns>     
        public static string tableToJson(DataTable dt, string tablename)
        {
            StringBuilder jsonBuilder = new StringBuilder();
            jsonBuilder.Append("\"");
            jsonBuilder.Append(tablename);
            jsonBuilder.Append("\":[");
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    jsonBuilder.Append("{");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        jsonBuilder.Append("\"");
                        jsonBuilder.Append(dt.Columns[j].ColumnName.ToLower());
                        jsonBuilder.Append("\":\"");
                        if (dt.Columns[j].DataType == typeof(DateTime))
                        {
                            String v = dt.Rows[i][j].ToString().Trim();
                            if (v != "")
                            {
                                DateTime d = DateTime.Now;
                                DateTime.TryParse(v, out d);
                                v = d.ToString("yyyy-MM-dd HH:mm:ss");
                            }
                            jsonBuilder.Append(v);
                        }
                        else
                        {
                            String v = dt.Rows[i][j].ToString().Trim();
                            v = v.Replace("\"", "\\\"").Replace("\r", "").Replace("\n", "").Replace("\\", "\\\\");
                            jsonBuilder.Append(v);
                        }
                        jsonBuilder.Append("\",");
                    }

                    jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                    jsonBuilder.Append("},");
                }
            }
            else
            {
                jsonBuilder.Append(",");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);

            jsonBuilder.Append("]");
            //jsonBuilder.Append("}");
            return jsonBuilder.ToString();
        }

        /// <summary>
        /// 获取数据流
        /// </summary>
        /// <returns></returns>
        public string getpost()
        {
            string g = "";
            if (HttpContext.Current.Request.InputStream != null)
            {
                System.IO.StreamReader sr = new System.IO.StreamReader(HttpContext.Current.Request.InputStream, System.Text.Encoding.UTF8);
                g = sr.ReadToEnd();
            }
            return g;
        }
        /// <summary>
        /// 从jobject中获取相应的数据 
        /// </summary>
        /// <param name="jobj">jobject对象</param>
        /// <param name="key">要获取的值</param>
        /// <returns></returns>
        public string jobject(JObject jobj, string key)
        {
            string hh = "";
            if (jobj[key] != null)
            {
                hh = jobj[key].ToString().Trim();
            }
            return hh;
        }

        #endregion

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        /// <summary>
        /// 保存照片的方法
        /// </summary>
        /// <param name="type"></param>
        /// <param name="sessionname"></param>
        /// <param name="typename"></param>
        /// <returns></returns>
        public static string savePic(string type)
        {
            string Path = "";
            try
            {
                string imgname = "product" + type + DateTime.Now.ToString("yyyyMMDDhhmmssff") + ".png";
                MemoryStream ms = (MemoryStream)HttpContext.Current.Session[type];
                //先把session的数据放入缓存流中再把缓存流放入文件流中
                string savepath = System.Web.HttpContext.Current.Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["indexPic"]);
                if (ms != null)
                {
                    if (!Directory.Exists(savepath))
                    {
                        //Directory是创建文件夹FileStream是写入和创建文件
                        Directory.CreateDirectory(savepath);
                    }
                    Path = System.Configuration.ConfigurationManager.AppSettings["indexPic"].Replace("~/", "") + "\\" + imgname;
                    using (Stream localFile = new FileStream(savepath + "\\" + imgname, FileMode.OpenOrCreate))
                    {
                        localFile.Write(ms.ToArray(), 0, (int)ms.Length);
                        localFile.Close();
                    }
                }
                return Path;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

        }

        /// <summary>
        /// 保存照片的方法
        /// </summary>
        /// <param name="type"></param>
        /// <param name="sessionname"></param>
        /// <param name="typename"></param>
        /// <returns></returns>
        public static string savePic2(string type)
        {
            string Path = "";
            try
            {
                string imgname = "product" + type + DateTime.Now.ToString("yyyyMMDDhhmmssff") + ".png";
                MemoryStream ms = (MemoryStream)HttpContext.Current.Session[type];
                MemoryStream mss = (MemoryStream)HttpContext.Current.Session["img2"];
                string savepath = System.Web.HttpContext.Current.Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["indexPic"]);
                if (ms != null)
                {
                    if (!Directory.Exists(savepath))
                    {
                        Directory.CreateDirectory(savepath);
                    }
                    Path = System.Configuration.ConfigurationManager.AppSettings["indexPic"].Replace("~/", "") + "\\" + imgname;
                    Stream stream = (Stream)ms;
                    System.Drawing.Image output = System.Drawing.Image.FromStream(stream);
                    Bitmap bmp = CImageLibrary.ChangeImgWH(130, 173, output);
                    bmp.Save(savepath + "\\" + imgname, output.RawFormat);
                }
                return Path;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

        }


    }
}